import { addClass, removeClass } from '../utils/assist';
import Vue from "vue"

const Transition = {
  beforeEnter(el: HTMLElement) {
    addClass(el, 'collapse-transition');
    // if (!el.dataset) el.dataset = {};

    el.dataset.oldPaddingTop = el.style.paddingTop;
    el.dataset.oldPaddingBottom = el.style.paddingBottom;

    el.style.height = '0';
    el.style.paddingTop = '0';
    el.style.paddingBottom = '0';
  },

  enter(el: HTMLElement) {
    el.dataset.oldOverflow = el.style.overflow;
    if (el.scrollHeight !== 0) {
      el.style.height = el.scrollHeight + 'px';
    } else {
      el.style.height = '';
    }
    if (el.dataset.oldPaddingTop)
      el.style.paddingTop = el.dataset.oldPaddingTop;
    if (el.dataset.oldPaddingBottom)
      el.style.paddingBottom = el.dataset.oldPaddingBottom;
    el.style.overflow = 'hidden';
  },

  afterEnter(el: HTMLElement) {
    // for safari: remove class then reset height is necessary
    removeClass(el, 'collapse-transition');
    el.style.height = '';
    if (el.dataset.oldOverflow)
      el.style.overflow = el.dataset.oldOverflow;
  },

  beforeLeave(el: HTMLElement) {
    //if (!el.dataset) el.dataset = {};
    el.dataset.oldPaddingTop = el.style.paddingTop;
    el.dataset.oldPaddingBottom = el.style.paddingBottom;
    el.dataset.oldOverflow = el.style.overflow;

    el.style.height = el.scrollHeight + 'px';
    el.style.overflow = 'hidden';
  },

  leave(el: HTMLElement) {
    if (el.scrollHeight !== 0) {
      // for safari: add class after set height, or it will jump to zero height suddenly, weired
      addClass(el, 'collapse-transition');
      el.style.height = "0";
      el.style.paddingTop = "0";
      el.style.paddingBottom = "0";
    }
  },

  afterLeave(el: HTMLElement) {
    removeClass(el, 'collapse-transition');
    el.style.height = '';
    if (el.dataset.oldOverflow)
      el.style.overflow = el.dataset.oldOverflow;
    if (el.dataset.oldPaddingTop)
      el.style.paddingTop = el.dataset.oldPaddingTop;
    if (el.dataset.oldPaddingBottom)
      el.style.paddingBottom = el.dataset.oldPaddingBottom;
  }
};

const CollapseTransition = Vue.extend({
  name: 'CollapseTransition',
  functional: true,
  props: {
    appear: Boolean
  },
  render(h, { children, props }) {
    const data = {
      on: Transition,
      props: {
        appear: props.appear
      }
    };

    return h('transition', data, children);
  }

})

export default CollapseTransition
